<template>
  <div>
    <van-button
      style="position: fixed; top: 30px; right: 0; z-index: 999"
      type="primary"
      >loading:{{ loading }}===finished:{{ finished }}===refreshing:{{
        refreshing
      }}
      <br />
      数组长度:{{ list.length }}</van-button
    >
    <van-pull-refresh v-model="refreshing" @refresh="onRefresh">
      <van-list
        :finished="finished"
        offset="80"
        @load="onLoad"
        finished-text="我是有底线的"
        v-model="loading"
      >
        <van-cell
          :key="index"
          :title="index + 1 + ',' + item.goods_name"
          v-for="(item, index) in list"
        />
      </van-list>
    </van-pull-refresh>
  </div>
</template>
<script>
/*
List组件通过 loading 和 finished 两个变量控制加载状态，
1.当组件滚动到底部时，会触发 load 事件并将 loading 设置成 true。此时可以发起异步操作并更新数据，数据更新完毕后，将 loading 设置成 false 即可。
2.若数据已全部加载完毕，则直接将 finished 设置成 true 即可。
*/
import axios from 'axios'
export default {
  data () {
    return {
      list: [],
      loading: false,
      finished: false,
      pagenum: 0,
      pagesize: 10,
      refreshing: false,
    };
  },
  methods: {
    onLoad () {
      // 异步更新数据
      /* 初次进入也会触发，上拉就触发 */
      // setTimeout(() => {
      //   for (var i = 0; i < 20; i++) {
      //     this.list.push(this.list.length + 1)
      //   }
      //   this.loading = false// 结束当前加载
      // }, 3000)

      if (this.pagenum > 3) {
        this.loading = false// 结束当前加载
        //结束上拉，设置值为true就表示不能上拉了
        this.finished = true
        return
      }
      this.pagenum++
      this.getaxios()
    },
    onRefresh () {
      // 清空列表数据
      this.finished = false;
      // 重新加载数据
      // 将 loading 设置为 true，表示处于加载状态
      // this.loading = true;
      this.pagenum = 0
      this.onLoad();
    },
    //发送ajax请求获取数据
    async getaxios () {
      const res = await axios({
        url: 'http://vue-shop-api-t.itheima.net/api/private/v1/goods',
        headers: {
          Authorization: 'Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1aWQiOjUwMCwicmlkIjowLCJpYXQiOjE2ODU0MzEyOTgsImV4cCI6MTY4NTUxNzY5OH0.rMLF5nxywTFwqBVP7RWyNJ_qEXoleuetLMbAHDz-NvI'
        },
        params: {
          pagenum: this.pagenum,
          pagesize: this.pagesize
        }
      })
      console.log(res);
      this.list = this.refreshing ? res.data.data.goods : this.list.concat(...res.data.data.goods)
      this.loading = false// 结束当前加载
      this.refreshing = false //当前加载接收,结束下拉
    }
  },
};
</script>
<style lang='less'  scoped>
</style>
